package org.openinsula.arena.aws.s3;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.jets3t.service.S3Service;
import org.jets3t.service.S3ServiceException;
import org.jets3t.service.impl.rest.httpclient.RestS3Service;
import org.jets3t.service.model.S3Bucket;
import org.jets3t.service.model.S3Object;
import org.jets3t.service.security.AWSCredentials;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;

public class DefaultS3Manager implements S3Manager, InitializingBean {

	private String accessKey;

	private String secretAccessKey;

	private S3Service s3Service;

	@Override
	public void afterPropertiesSet() throws Exception {
		Assert.notNull(accessKey, "'accessKey' must not be null.");
		Assert.notNull(secretAccessKey, "'secretAccessKey' must not be null.");

		AWSCredentials awsCredentials = new AWSCredentials(accessKey, secretAccessKey);

		s3Service = new RestS3Service(awsCredentials);
	}

	public byte[] get(String bucketName, String resourceName) throws S3ServiceException, IOException {
		S3Bucket bucket = s3Service.getBucket(bucketName);

		S3Object s3Object = s3Service.getObject(bucket, resourceName);

		InputStream in = s3Object.getDataInputStream();
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int i = 0;
		while ((i = in.read()) != -1) {
			baos.write(i);
		}
		in.close();
		baos.close();

		return baos.toByteArray();
	}

	public void put(String bucketName, String resourceName, byte[] data) throws S3ServiceException {
		S3Bucket bucket = s3Service.getOrCreateBucket(bucketName);

		S3Object s3Object = new S3Object(resourceName);

		s3Object.setDataInputStream(new ByteArrayInputStream(data));
		s3Object.setContentLength(data.length);
		s3Object.setContentType("text/plain");

		s3Service.putObject(bucket, s3Object);
	}

	public void setAccessKey(String accessKey) {
		this.accessKey = accessKey;
	}

	public void setSecretAccessKey(String secretAccessKey) {
		this.secretAccessKey = secretAccessKey;
	}

}
